﻿using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using Gp.Scripts.Core;
using QFramework;
using Sirenix.OdinInspector;
using UnityEngine;

namespace Gp.Scripts.GUI {
    [ExecuteAlways]
    public class OptionWindowController : MonoBehaviour {
        [SerializeField] private Material fadeMaterial;
        [SerializeField] [Range(0, 1)] private float fadeAmount;

        [SerializeField] private GameObject windowGroup;
        private static readonly int FadeAmount = Shader.PropertyToID("_FadeAmount");
        [SerializeField, Range(0, 1)] private float fadeTime = 1f;

        [Title("UI 设置")]
        [SerializeField] private OptionUIButton prefab;
        [SerializeField] public Sprite defaultIcon;


        private void Start() {
            // if (Application.isPlaying && Global.Get<GridBattleGUISystem>().OptionWindowController == null) {
                // Global.Get<GridBattleGUISystem>().OptionWindowController = this;
            // }
        }

        

        private bool Selected { get; set; }
        public IEnumerator GetOption(IEnumerable<OptionItem> items) {
            List<OptionUIButton> buttons = new();

            foreach (var item in items) {
                var obj = prefab.InstantiateWithParent(windowGroup.transform);
                obj.gameObject.SetActive(true);
                obj.Init(this);
                buttons.Add(obj);
                obj.RenderOption(item);
            }
            fadeAmount = 1;
            DOTween.To(() => fadeAmount, x => fadeAmount = x, 0, fadeTime);
            
            Selected = false;
            while (!Selected) {
                yield return 0;
            }

            
            foreach (var button in buttons) {
                Destroy(button.gameObject);
            }
        }


        public void OptionSelected(OptionUIButton button) {
            Selected = true;
        }
        
        

        private void Update() {
            fadeMaterial.SetFloat(FadeAmount, fadeAmount);
        }
    }

}